package dav.mobile.garuda.main;

import org.json.JSONException;
import org.json.JSONObject;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;

import dav.mobile.garuda.components.Constants;
import dav.mobile.garuda.components.Profile;
import dav.mobile.garuda.components.ResourceManager;
import dav.mobile.garuda.components.SoundManager;
import dav.mobile.garuda.components.Utilities;
import dav.mobile.garuda.states.*;

public class Main implements ApplicationListener {
	// Game flag
	private boolean m_Running = false;
	
	//Game attributes
	private State	m_State;
	
	public void SetState(State state) {
		if (m_State!=null) m_State.Dispose();
		
		m_State = state;
		m_State.Initialize(this);
	}
	
	@Override
	public void create() {
		//Load resource
		ResourceManager.Load();
		SoundManager.Load();
		
		//Load profile
		try {
			String JSON = Utilities.ReadJSON(Constants.GAME_PROFILE_FILE);
			if (JSON!=null) Profile.getInstance().LoadJSON(new JSONObject(JSON));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		//Set Flag
		m_Running = true;
		
		//set first state
		//SetState(new StateSplash());
		SetState(new StateGame("prolog",1));
	}

	@Override
	public void dispose() {
		ResourceManager.Dispose();
		SoundManager.Dispose();
	}

	@Override
	public void pause() {
		m_Running = false;
	}

	@Override
	public void render() {
		if (m_Running) {
			//Update 
			m_State.Update();
			
			//Clear buffer
			Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
			
			//Render
			m_State.Render();
		}
	}

	@Override
	public void resize(int width, int height) {	

	}

	@Override
	public void resume() {
		m_Running = true;
	}

}
